<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="(cartInfo) in cartInfoList" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" v-model="cartInfo.isChecked" @change="changeChecked(cartInfo,$event)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{cartInfo.skuName}}</div>
          </li>
          <li class="cart-list-con3">
            <div class="item-txt">语音升级款</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{cartInfo.skuPrice}}</span>
          </li>
          <li class="cart-list-con5">
            <!-- 传入的参数:1--确定点击的哪一项 2--接口所需参数 3--标记,区分点击的哪个按钮 -->
            <a href="javascript:void(0)" class="mins" @click="updata(cartInfo,-1,'miues')">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" class="itxt" @change="updata(cartInfo,$event.target.value,'input')">
            <a href="javascript:void(0)" class="plus" @click="updata(cartInfo,1,'add')">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{cartInfo.skuNum * cartInfo.skuPrice}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet" @click="deleteOne(cartInfo)">删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="check">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="deleteAllShop">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{totalShop}}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{totalPrice}}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" href="###" target="_blank">结算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import throttle from 'lodash/throttle'
  export default {
    name: 'ShopCart',
    methods: {
      getShopCartData(){
        this.$store.dispatch('getShopList')
      },
      //此函数调用时需要注意,快速点击会造成函数卡顿现象,使用节流
      //注意此时函数要使用普通函数
      //输入框更新商品数量
      updata:throttle(async function(shop,disNum,flag){
        //通过标记判断
        switch(flag){
          case "add":
            //如果是加
            disNum = 1;
            break;
          case "miues":
            //如果是减
            if(shop.skuNum <= 1){
              disNum = 0;
            }else{
              disNum = -1;
            }
            break;
          case "input":
            //判断其是否合法
            if(isNaN(disNum * 1) || disNum * 1 < 1){
              //此判断内是不合法数据的处理结果
              alert('请输入有效整数(不可小于1)');
              disNum = 0;
            }else{
              //此判断内是合法数字和小数的处理方法
              disNum = parseInt(disNum) - shop.skuNum;
            }
            break;
        }
        //发送请求,修改数据库中数据,此函数返回promise,判断是否修改成功
        try {
          await this.$store.dispatch('postShopCar',{skuId:shop.skuId,skuNum:disNum});
        //发送请求,获取最新的组件显示数据
          this.getShopCartData()
        } catch (error) {
          alert('修改失败')
        } 
      },500),
      //删除单个商品
      async deleteOne(shop){
        //通过派发的函数的返回值判断是否删除成功,若成功,则更新视图,获取最新数据
        try {
          await this.$store.dispatch('deleteCart',shop.skuId)
          this.getShopCartData()
        } catch (error) {
          alert('删除失败')
        }
      },
      //更改商品单选框
      async changeChecked(shop,event){
        let isChecked = event.target.checked ? '1' : '0';
        try {
          await this.$store.dispatch('changeChecked',{skuId:shop.skuId,isChecked})
          this.getShopCartData()
        } catch (error) {
          alert('更改失败')
        }
      },
      //删除选中的商品
      async deleteAllShop(){
        try {
          await this.$store.dispatch('deleteAllShop')
          this.getShopCartData()
        } catch (error) {
          alert('删除失败')
        }
      }
    },
    mounted() {
      this.getShopCartData()
    },
    computed: {
      ...mapGetters(['shopData']),
      cartInfoList(){
        return this.shopData.cartInfoList || []
      },
      //计算总价
      totalPrice(){
        let sum = 0;
        this.cartInfoList.forEach((item) => {
          if(item.isChecked){
            sum += item.skuNum * item.cartPrice;
          }
        })
        return sum
      },
      //计算选中商品的个数
      totalShop(){
        return this.cartInfoList.filter(item => {
          return item.isChecked == 1
        }).length
      },
      //计算属性,单选框的状态,全选框
      check:{
        get(){
          //确保购物车中有数据且都选中
          return this.cartInfoList.length > 0 && this.cartInfoList.every((item) => item.isChecked == 1)
        },
        async set(val){
          //val即为改变后的isChecked属性值
          //派发dispatch在仓库中逐个修改每个商品的选中状态
          let isChecked = val ? '1' : '0';
          try {
            //修改成功
            await this.$store.dispatch('updateChecked',isChecked)
            this.getShopCartData()
          } catch (error) {
            // 修改失败
            alert('修改失败')
          }
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  .cart {
    width: 1200px;
    margin: 0 auto;

    h4 {
      margin: 9px 0;
      font-size: 14px;
      line-height: 21px;
    }

    .cart-main {
      .cart-th {
        background: #f5f5f5;
        border: 1px solid #ddd;
        padding: 10px;
        overflow: hidden;

        &>div {
          float: left;
        }

        .cart-th1 {
          width: 25%;

          input {
            vertical-align: middle;
          }

          span {
            vertical-align: middle;
          }
        }

        .cart-th2 {
          width: 25%;
        }

        .cart-th3,
        .cart-th4,
        .cart-th5,
        .cart-th6 {
          width: 12.5%;

        }
      }

      .cart-body {
        margin: 15px 0;
        border: 1px solid #ddd;

        .cart-list {
          padding: 10px;
          border-bottom: 1px solid #ddd;
          overflow: hidden;

          &>li {
            float: left;
          }

          .cart-list-con1 {
            width: 4.1667%;
          }

          .cart-list-con2 {
            width: 25%;

            img {
              width: 82px;
              height: 82px;
              float: left;
            }

            .item-msg {
              float: left;
              width: 150px;
              margin: 0 10px;
              line-height: 18px;
            }
          }

          .cart-list-con3 {
            width: 20.8333%;

            .item-txt {
              text-align: center;
            }
          }

          .cart-list-con4 {
            width: 12.5%;

          }

          .cart-list-con5 {
            width: 12.5%;

            .mins {
              border: 1px solid #ddd;
              border-right: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }

            input {
              border: 1px solid #ddd;
              width: 40px;
              height: 33px;
              float: left;
              text-align: center;
              font-size: 14px;
            }

            .plus {
              border: 1px solid #ddd;
              border-left: 0;
              float: left;
              color: #666;
              width: 6px;
              text-align: center;
              padding: 8px;
            }
          }

          .cart-list-con6 {
            width: 12.5%;

            .sum {
              font-size: 16px;
            }
          }

          .cart-list-con7 {
            width: 12.5%;

            a {
              color: #666;
            }
          }
        }
      }
    }

    .cart-tool {
      overflow: hidden;
      border: 1px solid #ddd;

      .select-all {
        padding: 10px;
        overflow: hidden;
        float: left;

        span {
          vertical-align: middle;
        }

        input {
          vertical-align: middle;
        }
      }

      .option {
        padding: 10px;
        overflow: hidden;
        float: left;

        a {
          float: left;
          padding: 0 10px;
          color: #666;
        }
      }

      .money-box {
        float: right;

        .chosed {
          line-height: 26px;
          float: left;
          padding: 0 10px;
        }

        .sumprice {
          width: 200px;
          line-height: 22px;
          float: left;
          padding: 0 10px;

          .summoney {
            color: #c81623;
            font-size: 16px;
          }
        }

        .sumbtn {
          float: right;

          a {
            display: block;
            position: relative;
            width: 96px;
            height: 52px;
            line-height: 52px;
            color: #fff;
            text-align: center;
            font-size: 18px;
            font-family: "Microsoft YaHei";
            background: #e1251b;
            overflow: hidden;
          }
        }
      }
    }
  }
</style>